/**
 * Created by xc on 15/12/22.
 */

var common = require('../../common');
var pool = require('../index');
var mysql = require('mysql');
var ItbBaseModel = require('./ItbBaseModel');


// Schema 结构
var ItbGraphModel = function(obj){
    ItbBaseModel.call(this,obj);

  // 以下为表定义数据，需要的字段就填入
  //`graph_id` bigint(20) unsigned NOT NULL AUTO_INCREMENT COMMENT '图形ID',
  //`graph_type` int(3) DEFAULT NULL COMMENT '图形分类:0实心,1数字,2简单图形',
  //`graph_name` varchar(200) NOT NULL DEFAULT '' COMMENT '图形名称',
  //`user_id` bigint(20) NOT NULL COMMENT '用户ID',
  //`user_type` int(1) NOT NULL DEFAULT '0' COMMENT '0后台; 1用户',
  //`data` mediumtext NOT NULL COMMENT 'json数据',
  //`thumb` varchar(500) DEFAULT NULL COMMENT '缩略图',
  //`create_time` datetime NOT NULL,
  //`update_time` datetime NOT NULL,
  //`update_by` varchar(50) NOT NULL DEFAULT '',
  //`del_flg` int(1) NOT NULL DEFAULT '0',
  //`thumb_qn` varchar(500) DEFAULT NULL COMMENT 'qiniu 缩略图',

};
ItbGraphModel.prototype = new ItbBaseModel();

// 取得表名
ItbGraphModel.prototype.getTableName = function(){
    return 'itb_graph';
}
// 取得查询语句中where 后面匹配主键的条件（需要各派生类进行重载）
ItbGraphModel.prototype.getWhereConditionOfKeyEqual = function(){
    return 'graph_id='+this.graph_id;
}
// 查找相似的图标：分类相同、名称相近
// 参数：type 图形分类
// 参数：segments 多个图标一起查询，多个图标之间以","分隔，一个图标内部以"-"分隔,例如："银行-金融,工作-人员"
// 参数：delimiter_arr 多个文字的分隔符,一般为","
// 参数：delimiter_seg 文字的多个分词的分隔符,一般为"-"
// 参数：callback 回调，参数如下：
//          error:错误
//          rows:多行数据（行数与segments个数相等、顺序对应），每行数据包含：
//                      data:图标的轮廓数据
//                      graph_id:图标的id
ItbGraphModel.prototype.findLikenessGraph = function(type, segments, delimiter_arr,delimiter_seg , callback){
    var THIS = this;
    var tableName = this.getTableName();

    pool.pool.getConnection(function(err, connection) {
        // Use the connection
        var sql = 'CALL proc_find_likeness_graph('+type+',"'+segments+'","'+delimiter_arr+'","'+delimiter_seg+'");';

        console.log(sql);
        connection.query(sql, function(error, result) {
            // And done with the connection.
            connection.release();

            console.log("findLikenessGraph result is:\n"+result);

            if(error) {
                callback(error, result);
            } else {
                callback(null, result);
            }
        });
    });
}

// 根据ids批量查找graph
// 参数：ids (逗号分隔的graph_id)
// 参数：callback 回调，参数如下：
//          error:错误
//          result:多行数据
ItbGraphModel.prototype.findGraphByIds = function(callback){
    var THIS = this;
    var tableName = this.getTableName();

    pool.pool.getConnection(function(err, connection) {
        if (err) {
            console.log('ItbGraphModel.findGraphByIds Err:'+err);
        }
        // Use the connection
        var sql = 'SELECT * FROM itb_graph t WHERE t.del_flg = 0 AND t.graph_id IN ( ' +
            THIS.ids +
            ' ) ORDER BY t.graph_id ';
        //var sqlValue = [];
        //var sql = mysql.format(sql, sqlValue);
        console.log(sql);
        connection.query(sql, function(error, result) {
            // And done with the connection.
            connection.release();

            console.log();

            callback(error, result);
        });
    });
}

// 带关键字查找
// 参数：key, 关键字
// callback 参数：
//                error：错误
//                count：找到的个数
ItbGraphModel.prototype.findCountFromDBWithKey = function(key, callback){
    var THIS = this;
    var tableName = this.getTableName();
    var whereCondition = THIS.getWhereCondition() + ' and graph_name like "%'+key+'%"';
    // 从mysql中查询
    pool.pool.getConnection(function(err, connection) {
        var sql = "select count(*) as itemCount from "+tableName+" t1 where "+whereCondition;
        var sqlValue = [];
        var sql = mysql.format(sql, sqlValue);
        console.log(sql);

        // Use the connection
        connection.query(sql, function(error, items) {
            // And done with the connection.
            connection.release();

            var total=0;
            if(error) {
                console.log(error);
            } else if (items) {
                console.log('find item');
                total = items[0].itemCount;
            } else{
                console.log('find no one');
            }
            // 回调
            callback(error, total);
        });

    });

}

// 带关键字查找
// 参数：key, 关键字
// callback 参数：
//                error：错误
//                items：找到所有对象
ItbGraphModel.prototype.findFromDBWithKey = function(key, callback,skipCnt,pageSize){
    var THIS = this;
    var tableName = this.getTableName();
    var whereCondition = THIS.getWhereCondition() + ' and graph_name like "%'+key+'%"';
    // 从mysql中查询
    pool.pool.getConnection(function(err, connection) {
        var sql = "select *  from "+tableName+" t1 where "+whereCondition;
        if(typeof skipCnt!='undefined' && skipCnt != null && typeof pageSize!='undefined' && pageSize != null){
            sql += " limit " + Number(skipCnt) + "," + Number(pageSize);
        }
        var sqlValue = [];
        var sql = mysql.format(sql, sqlValue);
        console.log(sql);

        // Use the connection
        connection.query(sql, function(error, items) {
            // And done with the connection.
            connection.release();

            // 回调
            callback(error, items);
        });

    });

}


// 导出
module.exports = ItbGraphModel;